<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pro_pertanggungjwb_um2 extends MY_Controller {
	
	function __construct() {
		parent::__construct(); 
		
		$this->load->model('pro_pertanggungjwb_um2_model', 'UANG_MUKA');
		$this->secure_session();
	}

	function index() {
		$data['title'] = "Pertanggung Jawaban Uang Muka";
		$data['it_app']=$this->UANG_MUKA->GetApp();
		viewByTemplate('pro_pertanggungjwb_um2/index', $data, 'grid');
	}

	function getdata() {
		$this->secure_session();
		echo $this->UANG_MUKA->GetJSON();
		
	}

	function ajax_post() {
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try {
			if (count( $error->Get() ) > 0) { 
				$is_error = 1; 
			} else {
				// Fill Post Data
				$data	= post_by_key(array('cost_centre', 'jumlah_harga', 'harga_satuan', 'jumlah_satuan', 'keterangan'));
				$data['cost_centre']	= @ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim($data['cost_centre'])));
				
				if (post("mode") == "create") {
					//$data['tgl_rekam']	= NOW;
					//$data['user_rekam']	= USERID;

					$this->UANG_MUKA->Add($data);

					$ls_response = "Data Tersimpan";
					//App.audit_trail("CS001", "create/" + (data.app_id ?? ""));

				} else if (post("mode") == "edit") {
					//$data['tgl_ubah']	= NOW;
					//$data['user_ubah']	= USERID;
					
					$this->UANG_MUKA->Update($data, 
										array('cost_centre'	=> $data['cost_centre']));

					$ls_response = "Data Tersimpan";
					//App.audit_trail("CS002", "edit/" + (data.app_id ?? ""));

				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}

	private function validation() {
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");


		// Validation
		if (post("cost_centre") == '') {
			$error->Add("cost_centre", "Cost Centre", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT 1 FROM ADMIN_PRIMKOKAS.PRO_PERTANGGUNGJWB_UM2 WHERE COST_CENTRE = '".@ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim(post("COST_CENTRE"))))."'")) > 0) {
			$error->Add("cost_centre", "Cost Centre", $tpl_duplicate);
		}

		return $error;
	}

	function ajax_delete() {
		$ls_result	= "";
		$cost_centre	= get('cost_centre');
		if ($cost_centre != "") {
			// Delete Single
			$arr_rule	= array('cost_centre' => $cost_centre);
			$ls_result = $this->UANG_MUKA->DeleteSingle($arr_rule);

		} else {
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++) {
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('cost_centre' => $row['cost_centre']);
				$ls_result = $this->UANG_MUKA->DeleteSingle($arr_rule);
			}
		}
		
		echo $ls_result;
	}

	function download(){
		$filename			= APPPATH . '/file/cache/' . _SESSID.'.xls';
		@unlink($filename);
		$this->load->helper('file');
		
		$arr_alphabet	= array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EL', 'EK', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ');
		
		$ls_sql	= "	SELECT	*
					FROM 	mis_permintaan_um2
					ORDER BY cost_centre ASC";
						
						
		$result			= $this -> db -> query($ls_sql);
		$arr_data		= $result->result_array();
		
		if(count($arr_data)==0){ echo 'Data Empty..'; die; }
		
		require_once APPPATH . "third_party/PHPExcel.php";
		require_once APPPATH . "third_party/PHPExcel/IOFactory.php";
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();

		// Set properties
		$objPHPExcel->getProperties()->setCreator("Plitasoft")
									 ->setLastModifiedBy("Plitasoft")
									 ->setTitle("Office 2007 XLSX Import Data Document")
									 ->setSubject("Office 2007 XLSX Import Data Document")
									 ->setDescription("Import data document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Import result file");
		
		@set_time_limit(0);                   // ignore php timeout
		//@ignore_user_abort(true);             // keep on going even if user pulls the plug*
		
		$styleH1 = array('font' => array('bold' => true, 'size' => 18));
		$styleH2 = array('font' => array('bold' => true));
		
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'LIST DATA');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleH1);
		
		$ln_index	= 2;
		for($i=0,$max_i=count($arr_data); $i<$max_i; $i++){
			$row	= $arr_data[$i];
			if($i==0){ $arr_key	= array_keys($row); }
				
			// Add some data, we will use printing features
			// Header
			if($i==0){
				for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
					$field_name	= $arr_key[$j];
					
					$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
					$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $field_name);
					$objPHPExcel->getActiveSheet()->getStyle($ls_coordinate)->applyFromArray($styleH2);
				}
				$ln_index++;
			}
			
			// Data
			for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
				$field_name	= $arr_key[$j];
				$value		= $row[$field_name];
				
				$value	= str_replace("\t", '\t', $value);
				$value	= str_replace("\n",'\n', $value);
				$value	= str_replace(chr(10),'\n', $value);
				$value	= str_replace(chr(13),'\n', $value);
				if($j==4){ $value = strip_tags($value); }
				
				$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
				//echo $ls_coordinate.' ; ';
				$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $value);
			}
			$ln_index++;
		}
		
		
		// ------ >> Save EXCEL
		if(count($arr_data)>0){
			// Rename sheet
			//echo date('H:i:s') . " Rename sheet\n";
			$objPHPExcel->getActiveSheet()->setTitle('Sheet 1');
			
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);

			// Save Excel 2007 file
			//echo date('H:i:s') . " Write to Excel2007 format\n";
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save($filename);

		}
	}

	function download_sample_file(){
		$this -> secure_session();
		/* copyleft : http://elouai.com/force-download.php */
		
		$filename 			= APPPATH . '/../files/' . get('filename');
		$download_file_name	= $this->get_data("SELECT cost_centre FROM mis_permintaan_um2 WHERE cost_centre = '" . get('cost_centre') . "'");
		$download_file_name	= str_replace(':','.', str_replace(' ','_', str_replace('_NOW_', NOW, $download_file_name)));
		
		// required for IE, otherwise Content-disposition is ignored
		if(ini_get('zlib.output_compression'))
			ini_set('zlib.output_compression', 'Off');
		
		// addition by Jorg Weske
		$file_extension = strtolower(substr(strrchr($filename,"."),1));
		
		if($filename == "") 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: download file NOT SPECIFIED.');</script>";
			exit;
		} elseif ( ! file_exists( $filename ) ) 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: File $filename not found.');</script>";
			exit;
		};
		
		switch( $file_extension )
		{
			case "pdf": $ctype="application/pdf"; break;
			case "exe": $ctype="application/octet-stream"; break;
			case "zip": $ctype="application/zip"; break;
			case "doc": $ctype="application/msword"; break;
			case "xls": $ctype="application/vnd.ms-excel"; break;
			case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			case "gif": $ctype="image/gif"; break;
			case "png": $ctype="image/png"; break;
			case "jpeg":
			case "jpg": $ctype="image/jpg"; break;
			default: $ctype="application/force-download";
		}
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false); // required for certain browsers 
		header("Content-Type: $ctype");
		// change, added quotes to allow spaces in filenames, by Rajkumar Singh
		//header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
		header("Content-Disposition: attachment; filename=\"".$download_file_name."\";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($filename));
		readfile("$filename");
		exit();
	}

}
?>